package com.readywu.btchecker;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Utility {

    /**
     * change other activity
     * 
     * @param context
     *            this context
     * @param cls
     *            intent activity
     */
    public static void onStartActivity(Context context, Class<?> cls) {
        Intent intent = new Intent(context, cls);
        context.startActivity(intent);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     * 
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     * 
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String TwoLengthNum(int num) {
        DecimalFormat df = new DecimalFormat("00");
        String str = df.format(num);
        return str;
    }

    public static boolean isArrayDifferent(ArrayList<String> la,
            ArrayList<String> lb) {
        boolean diff = false;

        if (la == null)
            la = new ArrayList<String>();

        if (lb == null) {
            lb = new ArrayList<String>();
        }

        int aSize = la.size();
        int bSize = lb.size();
        lb.retainAll(la);
        if (lb.size() != aSize || lb.size() != bSize) {
            diff = true;
        }
        return diff;
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        int dividerHeight = listView.getDividerHeight();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        // listAdapter.getCount()返回数据项的数目
        int count = listAdapter.getCount();
        for (int i = 0, len = count; i < len; i++) {
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
            totalHeight += dividerHeight;
        }
        totalHeight += 10;
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (count - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    @SuppressLint("DefaultLocale")
    public static String getTimeDisplay(long timeInMillis) {
        if (timeInMillis <= 0) {
            return "";
        }
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(timeInMillis);

        String strTime = String.format("%d-%s-%s %s:%s:%s",
                time.get(Calendar.YEAR), pad(time.get(Calendar.MONTH) + 1),
                pad(time.get(Calendar.DAY_OF_MONTH)),
                pad(time.get(Calendar.HOUR_OF_DAY)),
                pad(time.get(Calendar.MINUTE)), pad(time.get(Calendar.SECOND)));
        return strTime;
    }

    @SuppressLint("DefaultLocale")
    public static String getDateDisplay(long timeInMillis) {
        if (timeInMillis <= 0) {
            return "";
        }
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(timeInMillis);

        String strTime = String.format("%d-%s-%s", time.get(Calendar.YEAR),
                pad(time.get(Calendar.MONTH) + 1),
                pad(time.get(Calendar.DAY_OF_MONTH)));
        return strTime;
    }

    public static String getMonthDayDisplay(long timeInMillis) {
        if (timeInMillis <= 0) {
            return "";
        }
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(timeInMillis);

        String strTime = String.format("%s/%s",
                pad(time.get(Calendar.MONTH) + 1),
                pad(time.get(Calendar.DAY_OF_MONTH)));
        return strTime;
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

    public static void setAlphaForView(View v, float alpha) {
        AlphaAnimation animation = new AlphaAnimation(alpha, alpha);
        animation.setDuration(0);
        animation.setFillAfter(true);
        v.startAnimation(animation);
    }

    public static void setEditTextSection(EditText editText, int lentgh) {
        if (null == editText) {
            return;
        }
        editText.setSelection(lentgh);
    }

    /**
     * Whether can connect the network.
     * 
     * @return
     */
    public static boolean isConnnection(Context context) {
        boolean isConnect = false;
        ConnectivityManager cManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cManager.getActiveNetworkInfo();
        if (null != networkInfo && networkInfo.isAvailable()) {
            isConnect = true;
        } else {
            isConnect = false;
        }

        return isConnect;
    }

    /**
     * 匹配格式： 11位手机号码 3-4位区号，7-8位直播号码，1－4位分机号 如：12345678901、1234-12345678-1234
     * 
     * @param phoneNumber
     * @return
     */
    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
        // String regex = "^13/d{9}||15[8,9]/d{8}$";
        String regex = "((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|"
                + "(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|"
                + "(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNumber);

        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

    public static String delHTMLTag(String htmlStr) {
        // 定义script的正则表达式
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>";
        // 定义style的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>";
        // 定义HTML标签的正则表达式
        String regEx_html = "<[^>]+>";

        Pattern p_script = Pattern.compile(regEx_script,
                Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 过滤script标签

        Pattern p_style = Pattern
                .compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 过滤html标签

        return htmlStr.trim(); // 返回文本字符串
    }

    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (null != v && (v instanceof EditText)) {
            int[] l = { 0, 0 };
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public static void setListViewHeight(ListView lv) {
        ListAdapter la = lv.getAdapter();
        if (null == la) {
            return;
        }
        int h = 0;
        // calculate height of all items.
        final int cnt = la.getCount();
        for (int i = 0; i < cnt; i++) {
            View item = la.getView(i, null, lv);
            item.measure(0, 0);
            h += item.getMeasuredHeight();
        }
        // reset ListView height
        ViewGroup.LayoutParams lp = lv.getLayoutParams();
        lp.height = h + (lv.getDividerHeight() * (cnt - 1));
        lv.setLayoutParams(lp);
    }

    /**
     * if the input is active,hide the editText.
     * 
     * @param context
     * @param editText
     */
    public static void hideInputManage(Context context, EditText editText) {
        InputMethodManager inputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive()) {
            inputMethodManager.hideSoftInputFromWindow(
                    editText.getWindowToken(), 0);
        }
    }

    public static String getApplicationPackage(Context context) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            String versionName = packageInfo.versionName;
            int versionCode = packageInfo.versionCode;
            String packageNames = packageInfo.packageName;
            return packageNames;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

}
